package com.playcrab.adouban.service;

import com.playcrab.adouban.util.Constants;

import com.playcrab.adouban.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log; 

public class UpdatesNotifier {

    private static final String LOG_TAG = "adouban:Notifier";

 
    /**
     * State of notification in the status bar. True if it is active now.
     */
    public static boolean notificationActive = false;
 

    public static void notifyDoumails(Context ctx, int doumailCount, boolean newEvents) {
        Log.v(LOG_TAG, "Updating notification info: " + doumailCount);

        // If user has cleared notification, we should create new one only if there were new events
        if (!notificationActive && !newEvents)
            return;
 

        String notificationText;
        Intent notificationIntent = null;

        if (doumailCount == 0) {
            clearNotification(ctx);
            return;
        } 
        else {
            notificationText = ctx.getString(R.string.notif_new_doumails);
        }

        StringBuilder text = new StringBuilder();
 
        Notification notification = new Notification(R.drawable.icon, notificationText, System.currentTimeMillis());
        // This intent will be thrown if user clears all notifications
        Intent deleteIntent = new Intent(Constants.ACTION_NOTIFICATION_CLEARED);
        notification.deleteIntent = PendingIntent.getBroadcast(ctx, 0, deleteIntent, 0);
 
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManager manager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, notification);

        notificationActive = true;
    }

    public static void clearNotification(Context ctx) {
        if (notificationActive) {
            NotificationManager manager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.cancel(1);
            notificationActive = false;
        }    
    }

}